package com.example.yiwei.crm.view.activity.clueActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.ContextThemeWrapper;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.clueDao;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetClue;
import com.example.yiwei.crm.data.GetClueData;
import com.example.yiwei.crm.dao_impl.clueDaoImpl;
import com.example.yiwei.crm.entity.ClueMeesageEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.view.activity.customerActivity.CustomerAddActivity;
import com.example.yiwei.crm.view.activity.customerActivity.CustomerAddBaseMessageActivity;
import com.example.yiwei.crm.view.activity.customerActivity.CustomerDetailedMessageActivity;
import com.example.yiwei.crm.view.frament.clueDetailedMenu.clueBaseFragment;
import com.example.yiwei.crm.view.frament.clueDetailedMenu.clueContactFragment;
import com.example.yiwei.crm.view.frament.clueDetailedMenu.clueOtherFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class ClueDetailedMessageActivity extends AppCompatActivity {
    FragmentManager manager;
    //声明碎片
    Fragment frm_base,frm_contact,fram_other;
    Button btn_base,btn_other,btn_contact;
    //声明选中哪个按钮的bolean值
    boolean ButtonTag2 =false;
    boolean ButtonTag1 =false;
    boolean ButtonTag4 =false;
    private PopupMenu popupMenu;
    private Menu menu;
    TextView txt_title_name,txt_title;
    ClueMeesageEntity clue;
    private ImageView img_update,img_call,img_message;
    String managerName,manger_number,manager_phone,manager_address,manager_job,addtional;
    int manger_id,department_id,manager_sort;
    public static ClueDetailedMessageActivity a;
     int clue_id;
    String [] names;
    String manager_name;
    String name;
    List<managerEntity> managerList;
    AlertDialog.Builder builder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clue_detailed_message);
        manager = getSupportFragmentManager();
        //初始化fragment
        frm_base=new clueBaseFragment();
        fram_other=new clueOtherFragment();
        frm_contact=new clueContactFragment();
        //初始化控件
        btn_base= (Button) findViewById(R.id.clue_detailed_base);
        btn_contact= (Button) findViewById(R.id.clue_detailed_contact);
        btn_other= (Button) findViewById(R.id.clue_detailed_other);
        txt_title_name= (TextView) findViewById(R.id.clue_detailed_txt_name);
        txt_title= (TextView) findViewById(R.id.clue_detailed_txt_title);
        img_update= (ImageView) findViewById(R.id.clue_detailed_img_update);
        img_call= (ImageView) findViewById(R.id.clue_detailed_img_call);
        img_message= (ImageView) findViewById(R.id.clue_detailed_img_message);
        a=this;

        clue= GetClue.get();
        img_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (clue.getClue_mobile_phone().equals("")){
                    Toast.makeText(ClueDetailedMessageActivity.this, "无联系人电话，请填写完整信息！", Toast.LENGTH_SHORT).show();
                }else{
                    callDialog();
            }
            }
        });
        img_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (clue.getClue_mobile_phone().equals("")){
                    Toast.makeText(ClueDetailedMessageActivity.this, "无联系人电话，请填写完整信息！", Toast.LENGTH_SHORT).show();
                }else{
                    messageDialog();
                }
            }
        });
        txt_title_name.setText(clue.getClue_name());
        OnClick(btn_base);
        //接收从simple页面传过来的值
        Intent intent=getIntent();
        clue_id=intent.getExtras().getInt("id");
        //初始化popmenu
        popupMenu = new PopupMenu(this, findViewById(R.id.clue_detailed_img_btn_plus));
        menu = popupMenu.getMenu();
        final MenuInflater inflater = getMenuInflater();
        if ("xiansuochi".equals(getIntent().getStringExtra("xiansuochiTag"))){
            txt_title.setText("线索池");
            //设置menu界面为res/menu/menu.xml
            inflater.inflate(R.menu.menu_clue_group,menu);
        }else {
            //设置menu界面为res/menu/menu.xml
            inflater.inflate(R.menu.menu_clue, menu);
        }
        //       下拉框监听方法
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    //删除
                    case R.id.clue_delete:
                     delete();
                        break;
                    //转化为客户
                    case R.id.clue_change1:
                        Intent intent=new Intent(ClueDetailedMessageActivity.this,CustomerAddActivity.class);
                        intent.putExtra("ClueToCustomerTag","ClueToCustomer");
                        startActivity(intent);
                        break;
                    //放入线索池
                    case R.id.clue_change2:
                       clueChange();
                        break;
                    //放入客户池
                    case R.id.clue_group_change2:
                        AlertDialog.Builder builder;
                        builder = new AlertDialog.Builder(new ContextThemeWrapper(ClueDetailedMessageActivity.this, R.style.custom_dialog));
                        builder.setTitle("您确定要放入客户池吗？");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent1=new Intent(ClueDetailedMessageActivity.this,CustomerAddActivity.class);
                                intent1.putExtra("ClueToCustomerGroupTag","ClueToCustomerGroup");
                                startActivity(intent1);
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                        builder.show();
                        break;
                    //转化为线索
                    case R.id.clue_group_change1:
                     if ("xiansuochi".equals(getIntent().getStringExtra("xiansuochiTag"))){
                         new Thread(new Runnable() {
                             @Override
                             public void run() {
                                 managerDao manaDao=new managerDaoImpl();
                                 managerList=manaDao.queryAllManager(baseClass.query_manager_url,null);
                                 List<String> name=new ArrayList<String>();
                                 for(int i=0;i<managerList.size();i++){
                                     manager_name=managerList.get(i).getManager_name();
                                     name.add(manager_name);
                                 }
                                 names=name.toArray(new String[name.size()]);
                                 runOnUiThread(new Runnable() {
                                     @Override
                                     public void run() {
                                         showDialog();
                                     }
                                 });
                             }
                         }).start();
                     }




                        break;

                }
                return false;
            }
        });
        img_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(ClueDetailedMessageActivity.this,ClueAddMessageActivity.class);
                intent.putExtra("tag","update");
                if ("xiansuochi".equals(getIntent().getStringExtra("xiansuochiTag"))){
                    intent.putExtra("xiansuochiTag","xiansuochi");
                }
                startActivity(intent);
            }
        });
    }
    public void messageDialog(){
        builder = new AlertDialog.Builder(new ContextThemeWrapper(ClueDetailedMessageActivity.this, R.style.custom_dialog));
        builder.setTitle("您确定要发送短信吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+clue.getClue_mobile_phone()));
                startActivity(intent);

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.show();
    }
    public void callDialog(){
        builder = new AlertDialog.Builder(new ContextThemeWrapper(ClueDetailedMessageActivity.this, R.style.custom_dialog));
        builder.setTitle("您确定要拨打电话吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + clue.getClue_mobile_phone());
                intent.setData(data);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.show();
    }
    public void showDialog() {
        //    设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉单选框的数据集合
         * 第二个参数代表索引，指定默认哪一个单选框被勾选上
         * 第三个参数给每一个单选项绑定一个监听器
         */
        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.custom_dialog));
        builder.setTitle("请选择负责人");
        builder.setSingleChoiceItems(ClueDetailedMessageActivity.this.names, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                managerName=names[which];
                name=managerList.get(which).getManager_name();
                manger_id=managerList.get(which).getManager_id();

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                         if (managerName.equals(name)){
                              new Thread(new Runnable() {
                                  @Override
                                  public void run() {
                                      JSONObject json = new JSONObject();
                                      try {
                                          json.put("XAA01",clue.getClue_id());
                                          json.put("XAA02",manger_id);
                                          json.put("XAA03",clue.getClue_name());
                                          json.put("XAA04",clue.getClue_gender());
                                          json.put("AKB01",clue.getClue_disease_category_id());
                                          json.put("XAA06",clue.getClue_contact());
                                          json.put("XAA08",clue.getClue_mobile_phone());
                                          json.put("AKD01",clue.getClue_channel_source_id());
                                          json.put("AKC01",clue.getClue_channel_classification_id());
                                          json.put("XAA13",clue.getClue_department_id());
                                          SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd  ");
                                          sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                                          if (clue.getClue_next_time()!=null&&clue.getClue_next_time()!="") {
                                              String next_time = clue.getClue_next_time();
                                          long l = Long.parseLong(next_time);
                                          Date date = new Date(l);
                                          String nTime = sdf.format(date);
                                          json.put("XAA14",nTime);
                                          }
                                          json.put("XAA15",clue.getClue_next_content());
                                          json.put("XAA16",clue.getClue_additional());

                                      } catch (JSONException e) {
                                          e.printStackTrace();
                                      }
                                      String str=json.toString();
                                      String result=NetWorkUtils.getCount(baseClass.update_clue_message_url,str);
                                      try {
                                          JSONObject object=new JSONObject(result);
                                          String boolen=object.getString("boolean");
                                          if ("success".equals(boolen)){
                                              List<ClueMeesageEntity> clueMeesageEntities;
                                              clueDao clueDao=new clueDaoImpl();
                                              clueMeesageEntities=clueDao.querySimpleClueMessage(baseClass.clue_group_url,null);
                                              //刷新
                                              GetClueData.CreateData();
                                              GetClueData.clue=clueMeesageEntities;
                                              if (GetClueData.clue!=null){
                                                  finish();
                                              }else{
                                                  Log.d("ddddd",boolen);
                                              }

                                          }
                                      } catch (JSONException e) {
                                          e.printStackTrace();
                                      }
                                  }
                              }).start();
                         }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

            }

        });

        builder.show();
    }
    //将线索放入线索池
    public void clueChange(){
        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.custom_dialog));
        builder.setTitle("您确定要放入线索池吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String str;
                        String results="";
                        JSONObject object=new JSONObject();
                        try {
                            object.put("XAA01",clue.getClue_id());
                            object.put("XAA03",clue.getClue_name());
                            object.put("XAA04",clue.getClue_gender());
                            object.put("AKB01",clue.getClue_disease_category_id());
                            object.put("XAA06",clue.getClue_contact());
                            object.put("XAA08",clue.getClue_mobile_phone());
                            object.put("AKD01",clue.getClue_channel_source_id());
                            object.put("AKC01",clue.getClue_channel_classification_id());
                            object.put("XAA13",clue.getClue_department_id());
                            SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd  ");
                            if (clue.getClue_next_time()!=null) {
                                String next_time = clue.getClue_next_time();
                                long l = Long.parseLong(next_time);
                                Date date = new Date(l);
                                String nTime = sdf.format(date);
                                object.put("XAA14",nTime);
                            }
                            object.put("XAA15",clue.getClue_next_content());
                            object.put("XAA16",clue.getClue_additional());

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        str=object.toString();
                        results=NetWorkUtils.getCount(baseClass.update_clue_message_url,str);
                        try {
                            JSONObject object1=new JSONObject(results);
                            String boolen=object1.getString("boolean");
                            if ("success".equals(boolen)){
                                List<ClueMeesageEntity> clueMeesageEntities;
                                clueDao clueDao=new clueDaoImpl();
                                clueMeesageEntities = clueDao.querySimpleClueMessage(baseClass.query_all_clue_message_ul, null);
                                //刷新
                                GetClueData.CreateData();
                                GetClueData.clue=clueMeesageEntities;
                                if (GetClueData.clue!=null){
                                    finish();
                                }else{
                                    Log.d("booleannnn",boolen);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.show();
    }
    //删除线索
    public void delete(){
        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.custom_dialog));
        builder.setTitle("您确定要删除吗？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        String result=NetWorkUtils.getCount(baseClass.delete_clue_message_url+clue_id,null);
                        try {
                            JSONObject jsonObject=new JSONObject(result);
                            String BOOLEAN=jsonObject.getString("boolean");
                            //删除成功返回simple页面刷新
                            if ("success".equals(BOOLEAN)){
                                List<ClueMeesageEntity> clueMeesageEntities;
                                clueDao clueDao=new clueDaoImpl();
                                if("xiansuochi".equals(getIntent().getStringExtra("xiansuochiTag"))){
                                    clueMeesageEntities=clueDao.querySimpleClueMessage(baseClass.clue_group_url,null);
                                }else {
                                    clueMeesageEntities = clueDao.querySimpleClueMessage(baseClass.query_all_clue_message_ul, null);
                                }
                                //刷新
                                GetClueData.CreateData();
                                GetClueData.clue=clueMeesageEntities;
                                if (GetClueData.clue!=null){
                                    finish();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
       builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
           @Override
           public void onClick(DialogInterface dialogInterface, int i) {

           }
       });
        builder.show();
    }
    public void OnClick(View view) {
        switch (view.getId()){
            case R.id.clue_detailed_base:
                //选中第一个按钮
                ButtonTag2=false;
                ButtonTag1 = true;
                ButtonTag4 = false;
                btn_base.setBackgroundColor(Color.parseColor("#FFFFFF"));
                btn_contact.setBackgroundColor(Color.parseColor("#E1E8ED"));
                btn_other.setBackgroundColor(Color.parseColor("#E1E8ED"));
                manager.beginTransaction().replace(R.id.clue_frame_conner,frm_base).commit();
                break;
            case R.id.clue_detailed_contact:
                //选中第二个按钮
                ButtonTag1 = false;
                ButtonTag2=true;
                ButtonTag4 = false;
                btn_base.setBackgroundColor(Color.parseColor("#E1E8ED"));
                btn_contact.setBackgroundColor(Color.parseColor("#FFFFFF"));
                btn_other.setBackgroundColor(Color.parseColor("#E1E8ED"));
                manager.beginTransaction().replace(R.id.clue_frame_conner,frm_contact).commit();
                break;
            case R.id.clue_detailed_other:
                //选中第三个按钮
                ButtonTag1 = false;
                ButtonTag2=false;
                ButtonTag4 = true;
                btn_base.setBackgroundColor(Color.parseColor("#E1E8ED"));
                btn_contact.setBackgroundColor(Color.parseColor("#E1E8ED"));
                btn_other.setBackgroundColor(Color.parseColor("#FFFFFF"));
                manager.beginTransaction().replace(R.id.clue_frame_conner,fram_other).commit();
                break;
            case R.id.clue_detailed_img_btn_plus:
                popupMenu.show();
                break;
            case R.id.clue_detailed_img_btn_back:
                finish();
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        clue=null;
        clue=GetClue.get();
        txt_title_name.setText(clue.getClue_name());
        if (ButtonTag1){
            frm_base=new clueBaseFragment();
            manager.beginTransaction().replace(R.id.clue_frame_conner,frm_base).commitAllowingStateLoss();
        }else if(ButtonTag2){
            frm_contact=new clueContactFragment();
            manager.beginTransaction().replace(R.id.clue_frame_conner,frm_contact).commitAllowingStateLoss();
        }else if(ButtonTag4){
            fram_other=new clueOtherFragment();
            manager.beginTransaction().replace(R.id.clue_frame_conner,fram_other).commitAllowingStateLoss();
        }
    }
}
